//
//  AppDelegate+Evoke.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/8/8.
//

import Foundation
import YPBedrock

extension AppDelegate {
    var host: String {
        return WmcNavigatorManager.shared.host
        // watermarkCamera
    }

    /// 通过universal link来唤起app
    func application(_ application: UIApplication,
                     continue userActivity: NSUserActivity,
                     restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool
    {
        guard let url = userActivity.webpageURL,
              let host = url.host else { return true }
        evokeLog("唤起方式：'Universal Link' Url：\(url)")
        let path = url.path
        var bol = true
        switch host {
        case "wmc.cdzbb.cn":
            if path.contains(WechatAppId){
                // 微信分享唤起 https://wmc.cdzbb.cn/watermarkCamera/wx8a7230a5ff99f638/...
                bol = wechatHandleOpenUniversalLink(application,
                                                    continue: userActivity,
                                                    restorationHandler: restorationHandler)
            }
        case "bsrd0v.jgmlink.cn",
             "bsrd0v.jmlk.co":
            bol = jmLinkHandleOpenUniversalLink(application,
                                                continue: userActivity,
                                                restorationHandler: restorationHandler)
        default: break
        }
        return bol
    }

    /// iOS9+，通过url scheme来唤起app
    func application(_ app: UIApplication,
                     open url: URL,
                     options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool
    {
        guard let _host = url.host else { return true }
        evokeLog("唤起方式：'Url Scheme' Url：\(url)")
        var bol = true
        
        if url.host == "pay" || url.host == "oauth" || url.host == "platformId=wechat" || url.host == "resendContextReqByScheme" {
            return WXApi.handleOpen(url, delegate: self)
        }
        
        switch _host {
        case host:
//            WmcNavigatorManager.push("home")
            break
        default:
            bol = jmLinkHandleOpen(app,
                                   open: url,
                                   options: options)
        }
        
        if !registerRangersAppID(url: url) {
            bol = false
        }
        
        return bol
    }

    /// 日志系统
    fileprivate func evokeLog(_ log: String) {
        WmcLogManager.DebugLog(type: .evoke, log: log)
    }
}
